//
//  MLAHomeVC.m
//  MagicLampApp
//
//  Created by Zheng on 2018/12/17.
//  Copyright © 2018 zheng.magic.lamp.app. All rights reserved.
//

#import "MLAHomeVC.h"
#import <SDCycleScrollView.h>
#import "MLAHomeCell.h"
#import "MLAHomeNewsDetailVC.h"
#import "MLAManageAdvertVC.h"
#import "MLAPropertySubletVC.h"
#import "MLAFundsPayableVC.h"
#import "MLAPropertyRepairVC.h"
#import "MLANewsModel.h"
#import "MLAHomeBannerModel.h"
#import "MLAWebVC.h"
#import "MLAPropertyVC.h"
#import "MLASavePinVC.h"
#import "MLAStoreHomeVC.h"
#import <CYLTabBarController.h>
#import "MLALoginVC.h"
#import "MLAManageAdvertVC.h"
#import "MLAManageBrandVC.h"
#import "WBQRCodeVC.h"
#import "MLAScanResultVC.h"

static NSInteger tag = 11000;

@interface MLAHomeVC () <SDCycleScrollViewDelegate>

@property (nonatomic, strong) UILabel *dateLbl;
@property (nonatomic, strong) SDCycleScrollView *cycleView;


@end

@implementation MLAHomeVC {
    NSMutableArray<MLANewsModel *> *newsArr;
    NSMutableArray<MLAHomeBannerModel *> *bannersArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.haveRefreshHeader = YES;
    
    [self addSubviewsInView];
    
    [self loadData];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
 
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    NSDate *date = [NSDate date];
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    format.dateFormat = @"MM月dd日";
    NSString *dateStr = [format stringFromDate:date];
    _dateLbl.text = dateStr;
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}




#pragma mark - LoadData
- (void)loadData {
    [super loadData];
    
    [MLAHttpManage postHostType:MLAHttpHostType_Api api:kNewsList params:nil success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        
        self.page++;
        self.haveRefreshFooter = YES;
        self->newsArr = [NSMutableArray array];
        self->newsArr = [MLANewsModel mj_objectArrayWithKeyValuesArray:response[@"lists"]];
        if (self->newsArr.count < 20) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        [self.tableView reloadData];
        
    } failure:^{
        
    }];
    
    [MLAHttpManage postHostType:MLAHttpHostType_Api api:kBannerList params:nil success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        self->bannersArr = [NSMutableArray array];
        self->bannersArr = [MLAHomeBannerModel mj_objectArrayWithKeyValuesArray:response[@"lists"]];
        NSMutableArray *imagesArr = [NSMutableArray array];
        for (MLAHomeBannerModel *model in self->bannersArr) {
            [imagesArr addObject:model.img_url];
        }
        self.cycleView.imageURLStringsGroup = [imagesArr copy];
    } failure:^{
        
    }];
}

- (void)loadMoreData {
    NSDictionary *params = @{@"page":@(self.page)};
    [MLAHttpManage postHostType:MLAHttpHostType_Api api:kNewsList params:params success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        
        self.page++;
        
        if ([response[@"lists"] count] < 20) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.tableView.mj_footer endRefreshing];
        }
        
        [self->newsArr addObjectsFromArray:[MLANewsModel mj_objectArrayWithKeyValuesArray:response[@"lists"]]];
        [self.tableView reloadData];
        
    } failure:^{
        
    }];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
    CX_Log(@"新闻详情");
    MLANewsModel *model = newsArr[indexPath.row];
    MLAHomeNewsDetailVC *hndVC = [[MLAHomeNewsDetailVC alloc] init];
    hndVC.modelId = model.modelId;
    [self.navigationController pushViewController:hndVC animated:YES];
}

#pragma mark - SDCycleScrollViewDelegate
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    MLAHomeBannerModel *model = bannersArr[index];
    MLAWebVC *webVC = [[MLAWebVC alloc] init];
    webVC.titleStr = model.name;
    webVC.urlStr = model.url;
    [self.navigationController pushViewController:webVC animated:YES];
}


#pragma mark - TableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return newsArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MLAHomeCell *cell = [tableView dequeueReusableCellWithIdentifier:kHomeCellID forIndexPath:indexPath];
    MLANewsModel *model = newsArr[indexPath.row];
    cell.model = model;
    return cell;
}


#pragma mark - Subviews
- (void)addSubviewsInView {
    
    self.tableView.rowHeight = 68.f;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[MLAHomeCell class] forCellReuseIdentifier:kHomeCellID];
    
    UIView *tableHeaderView = [[UIView alloc] init];
    tableHeaderView.frame = CGRectMake(0, 0, CX_GetScreenWidth(), 235+CX_GetXScale(485));
    
    
    _dateLbl = [[UILabel alloc] init];
    _dateLbl.textColor = CX_GetColorTitle();
    _dateLbl.font = CX_GetBoldFont(26);
    [tableHeaderView addSubview:_dateLbl];
    [_dateLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(50);
        make.left.mas_equalTo(15);
    }];
    
    UIButton *scanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [scanBtn setImage:[UIImage imageNamed:@"qr_scan"] forState:UIControlStateNormal];
    [scanBtn addTarget:self action:@selector(scanBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [tableHeaderView addSubview:scanBtn];
    [scanBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.dateLbl);
        make.right.offset(-5);
        make.width.height.offset(40);
    }];

    
    _cycleView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectZero delegate:self placeholderImage:nil];
    _cycleView.autoScrollTimeInterval = 3.f;
    [tableHeaderView addSubview:_cycleView];
    [_cycleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.dateLbl.mas_bottom).offset(20);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(CX_GetXScale(194));
    }];
    
    NSArray<NSDictionary *> *paysArr = @[@{@"title":@"扫一扫",
                                           @"image":@"home_top_0"},
                                         @{@"title":@"收款",
                                           @"image":@"home_top_1"},
                                         @{@"title":@"付款",
                                           @"image":@"home_top_2"}];
    
    NSMutableArray *topArrs = [NSMutableArray array];
    
    [paysArr enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:obj[@"title"] forState:UIControlStateNormal];
        [btn setTitleColor:CX_GetColorSubTitle() forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:obj[@"image"]] forState:UIControlStateNormal];
        btn.titleLabel.font = CX_GetNormalFont(12);
        btn.tag = tag+idx+10;
        [btn addTarget:self action:@selector(entryBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        CGFloat imageWidth = btn.imageView.image.size.width;
        CGFloat imageHeight = btn.imageView.image.size.height;
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        btn.imageEdgeInsets = UIEdgeInsetsMake(0, [obj[@"title"] length]*12/2., imageHeight, -([obj[@"title"] length]*12/2.));
        btn.titleEdgeInsets = UIEdgeInsetsMake(35, -imageWidth/2., 0, imageWidth/2.);
        [tableHeaderView addSubview:btn];
        [topArrs addObject:btn];
    }];

    [topArrs mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedItemLength:CGRectGetWidth(tableHeaderView.frame)/3.f leadSpacing:0 tailSpacing:0];
    [topArrs mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.cycleView.mas_bottom).offset(27);
        make.height.mas_equalTo(CX_GetXScale(100));
    }];

    
    UILabel *cateEnLbl1 = [[UILabel alloc] init];
    cateEnLbl1.textColor = CX_GetColorHex(0x6B7178, 1);
    cateEnLbl1.font = CX_GetNormalFont(10);
    cateEnLbl1.text = @"More features";
    [tableHeaderView addSubview:cateEnLbl1];
    [cateEnLbl1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.cycleView.mas_bottom).offset(125);
        make.left.mas_equalTo(15);
    }];
    
    UILabel *cateTitleLbl1 = [[UILabel alloc] init];
    cateTitleLbl1.textColor = CX_GetColorTitle();
    cateTitleLbl1.font = CX_GetNormalFont(16);
    cateTitleLbl1.text = @"更多功能";
    [tableHeaderView addSubview:cateTitleLbl1];
    [cateTitleLbl1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(cateEnLbl1.mas_bottom).offset(5);
        make.left.mas_equalTo(15);
    }];
    
    UIView *moreView = [[UIView alloc] init];
    moreView.frame = CGRectMake(0,0,CX_GetXScale(345),CX_GetXScale(165));
    moreView.backgroundColor = [UIColor whiteColor];
    moreView.layer.shadowColor = CX_GetColorHex(0x5C9EEB, 0.3).CGColor;
    moreView.layer.shadowOffset = CGSizeMake(0, 1);
    moreView.layer.shadowOpacity = 1;
    moreView.layer.cornerRadius = 5;
    [tableHeaderView addSubview:moreView];
    [moreView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(CX_GetXScale(165));
        make.top.equalTo(cateTitleLbl1.mas_bottom).offset(20);
    }];
    
    NSArray<NSDictionary *> *infosArr = @[@{@"title":@"开铺/打烊",
                                            @"image":@"home_btio_0"},
                                          @{@"title":@"缴费",
                                            @"image":@"home_btio_1"},
                                          @{@"title":@"物业服务",
                                            @"image":@"home_btio_2"},
                                          @{@"title":@"行政事务",
                                            @"image":@"home_btio_3"},
                                          @{@"title":@"进销存",
                                            @"image":@"home_btio_4"},
                                          @{@"title":@"广告位",
                                            @"image":@"home_btio_5"},
                                          @{@"title":@"品牌入驻",
                                            @"image":@"home_btio_6"},
                                          @{@"title":@"更多",
                                            @"image":@"home_btio_7"}];
    
    NSMutableArray *btnsArr = [NSMutableArray array];
    
    [infosArr enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:obj[@"title"] forState:UIControlStateNormal];
        [btn setTitleColor:CX_GetColorSubTitle() forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:obj[@"image"]] forState:UIControlStateNormal];
        btn.titleLabel.font = CX_GetNormalFont(12);
        btn.tag = tag+idx;
        btn.frame = CGRectMake(CGRectGetWidth(moreView.frame)/4.*(idx%4), CGRectGetHeight(moreView.frame)/2.*(idx/4), CGRectGetWidth(moreView.frame)/4., CGRectGetHeight(moreView.frame)/2.);
        [btn addTarget:self action:@selector(entryBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        CGFloat imageWidth = btn.imageView.image.size.width;
        CGFloat imageHeight = btn.imageView.image.size.height;
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        btn.imageEdgeInsets = UIEdgeInsetsMake(0, [obj[@"title"] length]*12/2., imageHeight, -([obj[@"title"] length]*12/2.));
        btn.titleEdgeInsets = UIEdgeInsetsMake(35, -imageWidth/2., 0, imageWidth/2.);
        [moreView addSubview:btn];
        [btnsArr addObject:btn];
    }];
    
//    [btnsArr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedItemLength:CGRectGetWidth(moreView.frame)/4.f leadSpacing:0 tailSpacing:0];
//    [btnsArr mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(moreView);
//        make.height.equalTo(moreView).multipliedBy(0.5);
//    }];
    
    UILabel *cateEnLbl2 = [[UILabel alloc] init];
    cateEnLbl2.textColor = CX_GetColorHex(0x6B7178, 1);
    cateEnLbl2.font = CX_GetNormalFont(10);
    cateEnLbl2.text = @"News details";
    [tableHeaderView addSubview:cateEnLbl2];
    [cateEnLbl2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(moreView.mas_bottom).offset(20);
        make.left.mas_equalTo(15);
    }];

    UILabel *cateTitleLbl2 = [[UILabel alloc] init];
    cateTitleLbl2.textColor = CX_GetColorTitle();
    cateTitleLbl2.font = CX_GetNormalFont(16);
    cateTitleLbl2.text = @"新闻详情";
    [tableHeaderView addSubview:cateTitleLbl2];
    [cateTitleLbl2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(cateEnLbl2.mas_bottom).offset(5);
        make.left.mas_equalTo(15);
    }];

    self.tableView.tableHeaderView = tableHeaderView;
    [tableHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(0);
        make.width.mas_equalTo(CX_GetScreenWidth());
        make.height.mas_equalTo(CGRectGetHeight(tableHeaderView.frame)).priorityHigh();
    }];
}

#pragma mark - Actions
- (void)entryBtnAction:(UIButton *)sender {
    
    
    NSString *token = [CX_GetUserDefaults() objectForKey:kAccessToken];
    
    if (!token) {
        MLALoginVC *loginVC = [[MLALoginVC alloc] init];
        [self.navigationController pushViewController:loginVC animated:YES];
        return;
    }
        
    NSInteger index = sender.tag - tag;
    if (index == 0) {
        MLAStoreHomeVC *storeVC = [[MLAStoreHomeVC alloc] init];
        [self.navigationController pushViewController:storeVC animated:YES];
    } else if (index == 1) {
        MLAFundsPayableVC *payableVC = [[MLAFundsPayableVC alloc] init];
        [self.navigationController pushViewController:payableVC animated:YES];
    } else if (index == 2) {
        MLAPropertyVC *property = [[MLAPropertyVC alloc] init];
        [self.navigationController pushViewController:property animated:YES];
    } /*else if (index == 3) {
        //行政事务
    }*/ else if (index == 4) {
        MLASavePinVC *spVC = [[MLASavePinVC alloc] init];
        [self.navigationController pushViewController:spVC animated:YES];
    } else if (index == 5) {
        MLAManageAdvertVC *maVC = [[MLAManageAdvertVC alloc] init];
        [self.navigationController pushViewController:maVC animated:YES];
    } else if (index == 6) {
        MLAManageBrandVC *mbVC = [[MLAManageBrandVC alloc] init];
        [self.navigationController pushViewController:mbVC animated:YES];
    } else if (index == 10) {
        [self scanBtnAction];
    } else if (index == 11) {
        MLAScanResultVC *srVC = [[MLAScanResultVC alloc] init];
        srVC.isPayCode = YES;
        [self.navigationController pushViewController:srVC animated:YES];
    }
    /*else if (index == 7) {
    }*/ else {
        [MLAHudManage showMessage:@"功能暂未开放，敬请期待"];
    }
    
    
//    else if (index == 10) {
//    } else if (index == 11) {
//    } else if (index == 12) {
//    }
    
    
}

- (void)scanBtnAction {
    WBQRCodeVC *codeVC = [[WBQRCodeVC alloc] init];
    [self.navigationController pushViewController:codeVC animated:YES];
}

@end
